<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\api\model\Content;
use think\Exception;

/**
 * 会员接口
 */
class Ticker extends Api
{

    protected $noNeedLogin = ['create','getContentByTicker'];
    protected $noNeedRight = '*';
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new Content;
    }

    /**
     * 创建
     * @param string $title
     * @param string $remark
     * @return string
     */
    public function create($title='INUTAN',$remark='')
    {
        $ticker = $this->_mkTicker();
        $file = request()->file('image');
        $info = $file->move( '.' .DIRECTORY_SEPARATOR . 'uploads');
        if($info){
            $image =  $info->getPathname();
            $pathInfo = pathinfo($image);
            $thumbPath = $pathInfo['dirname']. DIRECTORY_SEPARATOR . 'thumb_' . $pathInfo['basename'];
            $_image = \think\Image::open($image);
            $_image->thumb(250, 250)->save($thumbPath,null,70);
            $time = time();
            $in  =  60 * 60 * 2;
            $data = [
                'title' => $title,
                'ticker' => $ticker,
                'remark' => $remark,
                'image' => str_replace('.' .DIRECTORY_SEPARATOR,'/' ,$image),
                'thumb_image' => str_replace('.' .DIRECTORY_SEPARATOR,'/',$thumbPath),
                'status'=> 2,
                'create_time'=> $time,
                'expire_time'=> $time + $in,
                'expire_in'=> $in
            ];
            if(!$this->model->save($data)){
                $this->error('','',3001);
            }
            unset($data['image']);
            unset($data['remark']);
            $this->success('',$data,200);
        }else{
            $this->error('','',3002);
        }
    }

    /**
     * 根据ticker获取内容
     * @param string $ticker
     */
    public function getContentByTicker($ticker = ''){
        if(!$ticker){
            $this->error('','',3003);
        }
        $_ticker = $this->model->getContentByTicker($ticker);
        if(time() > $_ticker->expire_time){
            $_ticker->ticker = 'time out';
            $_ticker->save();
            $this->error('已超时','',3004);
        }else{
            $this->success('',$_ticker);
        }
    }

    /**
     * 创建ticker
     * @param int $ticker
     * @return int|string
     */
    private function _mkTicker($ticker= 5038){
        $flag = true;
        $_ticker = '';
        $i = 0 ;
        while ($flag){
            if($i == 0 && $ticker){
                $_ticker = $ticker;
            }else{
                $_ticker = \fast\Random::numeric(4);
            }
            $in_ticker = $this->model->where('ticker', 'eq', $_ticker)->find();
            if($in_ticker){
                $flag = true;
                $i++;
            }else{
                $flag = false;
            }
        }
        return $_ticker;
    }
}
